
package com.scalar.chiptrack.sales.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;


/**
 * Implementation of <strong>Action</strong> that gives customers list,
 * search with customer name, create, modify and delete customer
 *
 * @author Kesava Kumar Achanala
 * @version $Revision: 1.3 $ $Date: 2011/01/31 17:51:22 $
 */

public final class CustomerListAction extends ChipTrackAction
{
    private static final String ACTION_NAME = "/customersList.do" ;

    /**
     * Process the specified HTTP request, and create the corresponding HTTP
     * response (or forward to another web component that will create it).
     * Return an <code>ActionForward</code> instance describing where and how
     * control should be forwarded, or <code>null</code> if the response has
     * already been completed.
     *
     * @param mapping The ActionMapping used to select this instance
     * @param form The optional ActionForm bean for this request (if any)
     * @param request The HTTP request we are processing
     * @param response The HTTP response we are creating
     *
     * @exception Exception if business logic throws an exception
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
    {

        String customerName 		= null;
        ArrayList customersList 	= new ArrayList();
        String action = request.getParameter( "action" );

		request.setAttribute( "ShowTable", "TRUE" );
		request.setAttribute( "AllEmpty", "FALSE" );
		
		if( action == null ) 
		{
			action = "GetAllCustomers";
		}

        //Get the session, to retrieve the values
		HttpSession session = request.getSession();
        User user = (User)session.getAttribute (SessionKeys.USER_KEY);
        
        if( user == null )
		{
	    	session.setAttribute( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString() );
			return (mapping.findForward( "login" ) );
		}
        
		String showModify = "FALSE"; 
		String showDelete = "FALSE"; 

		if( user.isActionAllowed( Functionality.CUSTOMER_DETAILS, User.USER_ACTION_MODIFY ) )
			showModify = "TRUE";
		if( user.isActionAllowed( Functionality.CUSTOMER_DETAILS, User.USER_ACTION_DELETE ) )
			showDelete = "TRUE";

		request.setAttribute( "showModify", showModify );
		request.setAttribute( "showDelete", showDelete );

		// Validate the request parameters specified by the user
		HashMap<String, String> errors = new HashMap<String, String>();
		HashMap<String, String> info = new HashMap<String, String>();

		if( "GetAllCustomers".equals( action ) ) 
		{
            customersList = new ArrayList();
			request.setAttribute( "ShowTable", "FALSE" );
		}

		if( "DeleteCustomer".equals( action ) ) 
		{
			//This value is getting from the LinkCustomerTag
			int customerId = Integer.parseInt( request.getParameter( "customerId" ) );

			CustomerDAO.deleteCustomer( customerId );

			customersList = CustomerDAO.getAllCustomers();
		}

		if( "SearchCustomer".equals( action ) ) 
		{
			customerName 		= (String)BeanUtils.getSimpleProperty( form, "customerName" );
			String region 		= (String)BeanUtils.getSimpleProperty( form, "region" );
			String repOffice 	= (String)BeanUtils.getSimpleProperty( form, "repOffice" );
            String customerType = BeanUtils.getSimpleProperty( form, "customerType" );

			customersList = CustomerDAO.getAllCustomers( customerName, region, repOffice, customerType );
			
			if( ( customerName == null || customerName.length() == 0 ) && ( region == null || region.length() == 0 ) && ( repOffice == null || repOffice.length() == 0 ) )
		    {
				if( ( customersList == null ) || (customersList.size() == 0 ) )
				{
					 errors.put( ERROR_NO_CUSTOMER_EXIST, null );
					 customersList = new ArrayList();
					 request.setAttribute ( "AllEmpty", "TRUE" );
				}
			}
			else
			{
				if( ( customersList == null ) || ( customersList.size() == 0 ) )
				{
					 errors.put( ERROR_CUSTOMER_NOT_FOUND, null );
					 customersList = new ArrayList();
					 request.setAttribute ( "AllEmpty", "TRUE" );
				}
			}
		}
        else if ("updatenewCustomers".equalsIgnoreCase(action) )
        {
            try
            {
                JobHandler handler = (JobHandler) Class.forName( "com.scalar.chiptrack.adaptor.sitime.CustomerDataParser" ).newInstance();
                handler.execute();
                info.put("Successfully updated customer details", null);
            }
            catch(Exception e)
            {
                errors.put("Unable to update the new customer details", null);
                e.printStackTrace();
            }
        }

		// Report any errors we have discovered back to the original form
		if( !errors.isEmpty() ) 
		{
			request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);
		}
        if( !info.isEmpty() )
		{
			request.setAttribute(SessionKeys.INFO_MESSAGES, info);
		}
        //Set all the attributes in the request....
        request.setAttribute( "regions", CustomerDAO.getAllRegionNames() );
        request.setAttribute( "repOffices", CustomerDAO.getAllRepOfficesForCustomer() );
        request.setAttribute( "customerslist", customersList );
        request.setAttribute( "customerTypes", CustomerDAO.getAllCustomerTypeList( null ) );

		// Forward control to the specified success URI
        return ( mapping.findForward( "success" ) );
    }
}
